from contextlib import contextmanager

from loguru import logger
from pydantic import ConfigDict
from sqlmodel import Session, SQLModel

from app.api.database.service import DatabaseService
from settings import env_settings

db_service: DatabaseService = DatabaseService(env_settings.database_url)


@contextmanager
def session_getter() -> Session:
    """轻量级session context"""
    print("开始获取session", db_service.engine)
    try:
        session = Session(db_service.engine)
        print("已经获取到session", db_service.engine)
        yield session
    except Exception as e:
        logger.info('Session rollback because of exception:{}', e)
        session.rollback()
        raise
    finally:
        session.close()


class SQLModelSerializable(SQLModel):
    model_config = ConfigDict(from_attributes=True)
